import axios from 'axios'
import qs from 'qs'
// 创建axios实例 axiso的一些基础参数配置,
const instance = axios.create({
    // 配置在config/prod.env里的baseApi
    baseURL: import.meta.env.VUE_APP_API_URL,
    withCredentials: false,
    crossDomain: true,
    timeout: 5000, // 超时时间(ms)
    retry: 3, //重新请求次数
    retryDelay: 1000 //重新请求的间隙
})

// 请求拦截器 TODO
instance.interceptors.request.use(
    req => {
        // TODO
        const { headers, method, params } = req
        // 设置授权的TOKEN
        headers.AuthorizationToken = 'store.state.auth.accessToken'
        // 过滤空参数 TODO
        const keys = Object.keys(params)
        for (let key of keys) {
            const value = params[key]
            if (value === undefined || value === null || value === '') {
                delete params[key]
            }
        }
        // 判断为post请求，序列化传来的参数
        if (method === 'post') {
            req.data = qs.stringify(req.data, {
                arrayFormat: 'indices',
                allowDots: true
            })
        } else if (method === 'put') {
            console.error('use put method do it')
            console.error('不格式化成URL参数')
        } else if (method === 'patch') {
            req.data = qs.stringify(req.data, {
                arrayFormat: 'repeat', // ids=1&ids=2
                allowDots: true
            })
        }
        return req
    },
    error => {
        //TODO
        return Promise.reject(error)
    }
)
// 响应拦截器 TODO
instance.interceptors.response.use(
    res => {
        const { status, data } = res
        console.info(status)
        // 直接回输出内容
        return data
    },
    err => {
        const { message, code, status } = err
        console.error(message+ '|'+code+ '|'+ status+'|')
        if (status == 404) {
            console.error(code)
        }
        return message //Promise.reject(err)
    }
)
export default instance